﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using SystemSettings;
using Ionic.Zip;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.Instrument.Forms;
using Labthink.PCSoft.UniversalHost4.Instrument.Model;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Query;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using NLog;
using Report;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class UcHistoryData
    {
        private readonly QueryData _queryData;
        private bool _isLoaded;
        private const string ExportPath = @"labthink\back";
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        public bool IsSign { get; set; }
        public bool IsGmp { get; set; }

        public bool HasMultiCups { get; set; }
        public bool DataShield { get; set; }

        private NotifyManager _notify;
        private int _loadCount;

        public UcHistoryData()
        {
            _logger.Debug("装载历史数据控件");
            InitializeComponent();
            _logger.Debug("设置默认焦点");
            BtnQuery.Focus();
            _logger.Debug("初始化查询条件");
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                _queryData = new QueryData { PageCount = 10, PageIndex = 1 };
            }

            _logger.Debug("获取系统设置功能");
        }

        private void UcHistoryData_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            _loadCount++;
            _notify = NotifyManager.InstanceManager(Application.Current.MainWindow);
            IsSign = Common.IsSign;
            BtnUpload.Visibility = DataShield ? Visibility.Visible : Visibility.Collapsed;
            BtnUploadRecord.Visibility = DataShield ? Visibility.Visible : Visibility.Collapsed;
            BtnDelete.Visibility = IsGmp ? Visibility.Collapsed : Visibility.Visible;
            if (IsGmp)
            {
                Sign.Visibility = IsSign ? Visibility.Visible : Visibility.Collapsed;
                BtnSign.Visibility = IsSign ? Visibility.Visible : Visibility.Collapsed;
                if (IsSign && Sign.CbbChildBox.Items.Count == 0)
                {
                    var slts = new List<RtdData> { new RtdData { No = -1, Data1 = "--" } };
                    for (int i = 0; i <= 3; i++)
                    {
                        slts.Add(new RtdData { No = i, Data1 = LanguageManager.GetLanguageValue("ESignaled" + i) });
                    }

                    Sign.CbbChildBox.ItemsSource = slts;
                    Sign.CbbChildBox.DisplayMemberPath = "Data1";
                    Sign.CbbChildBox.SelectedValuePath = "No";
                }
            }
            else
            {
                Sign.Visibility = Visibility.Collapsed;
                BtnSign.Visibility = Visibility.Collapsed;
                Sign.Visibility = Visibility.Collapsed;
            }

            ColSign.Visibility = BtnSign.Visibility;
            if (_loadCount > 1 && GridData.Items.Count == 0)
            {
                BtnQuery_OnClick(null, null);
            }

            if (_isLoaded) return;
            _isLoaded = true;
            HasMultiCups = true;
            IsGmp = Common.BaseInfo.Gmp;
            DataShield = Common.BaseInfo.DataShield;

            _queryData.PageCount = Math.Max(_queryData.PageCount, Common.MaxCupCount);

            InitFrame();

            pager.OnPageIndexChanged += (s, a) =>
            {
                _queryData.PageIndex = pager.PageIndex;
                _initDatas();
            };

            pager.ItemCountPerPage = 10;
            //BtnQuery_OnClick(null, null);
        }

        private void GridData_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!(GridData.SelectedItem is TestIndex ti)) return;
            if (IsGmp)
            {
                var login = new FrmAuth();
                var dr = login.ShowDialog(Application.Current.MainWindow);
                if (dr == null || !dr.Value) return;
            }

            TriggerButtonsStatus(false);

            //获取所选文件
            var files = GetFiles(new List<string>
            {
                ti.FilePath
            });

            if (files == null || files.Count == 0)
            {
                TriggerButtonsStatus(true);
                return;
            }

            var manager = ReportManager2.Create();
            manager.Clear();
            manager.AddInfo(IsSign ? LanguageManager.GetLanguageValue("ESignaled" + ti.ESignal) : "", Common.CurrentUser.UserName + " " + DateTime.Now.ToShortDateString());
            manager.AddFile(files.First());

            TriggerButtonsStatus(true);
            var report = new FrmReport2
            {
                IsGmp = IsGmp,
                Manager = manager
            };

            report.ShowDialog(Application.Current.MainWindow);
        }

        private void BtnQuery_OnClick(object sender, RoutedEventArgs e)
        {
            _queryData.PageIndex = 1;
            _queryData.TestName = TestName.Value;
            _queryData.SampleName = SampleName.Value;
            _queryData.SampleBatch = SampleBatch.Value;
            _queryData.SampleNo = SampleNo.Value;
            _queryData.TestType = TestType.CbbChildBox.SelectedValue?.ToInt();
            _queryData.End = EndTime?.DpPicker.SelectedDate;
            _queryData.OpName = OpName.Value;
            _queryData.Remark = Remark.Value;
            _queryData.SampleMaterial = SampleMaterial.Value;
            _queryData.Start = StartTime.DpPicker.SelectedDate;
            _queryData.Tag = Tag1.Value;
            if (Common.SelfQuerys != null)
            {
                _queryData.SelfQuery = new List<FullData>();
                foreach (var sq in Common.SelfQuerys)
                {
                    if (!(WpQuerys.FindName("Cbb" + sq.ColumnName) is UcComboBox cbb))
                    {
                        sq.Value = -1;
                    }
                    else
                    {
                        sq.Value = cbb.CbbChildBox.SelectedValue;
                    }
                    _queryData.SelfQuery.Add(sq);
                }
            }

            if (Sign.Visibility == Visibility.Visible)
                _queryData.Sign = Sign.CbbChildBox.SelectedValue?.ToInt();

            _initDatas();
        }

        private void BtnReport_OnClick(object sender, RoutedEventArgs e)
        {
            var index = GetSelectedItems();
            if (!index.Any()) return;

            if (index.Count > 1)
            {

            }
            else
            {
                if (IsGmp)
                {
                    var login = new FrmAuth();
                    var dr = login.ShowDialog(Application.Current.MainWindow);
                    if (dr == null || !dr.Value) return;
                }

                TriggerButtonsStatus(false);
                //获取所选文件
                var files = GetFiles(new List<string>
                {
                    index.First().FilePath
                });

                if (files == null || files.Count == 0)
                {
                    TriggerButtonsStatus(true);
                    //MessageBox.Show(Resources.GetLanguageValue("DownloadFilesError"));
                    _notify.ShowError(LanguageManager.GetLanguageValue("DownloadFilesError"));
                    return;
                }

                var manager = ReportManager2.Create();
                manager.Clear();
                manager.AddInfo(IsSign ? LanguageManager.GetLanguageValue("ESignaled" + index.First().ESignal) : "", Common.CurrentUser.UserName + " " + DateTime.Now.ToShortDateString());
                manager.AddFile(files.First());

                TriggerButtonsStatus(true);
                var report = new FrmReport2
                {
                    IsGmp = IsGmp,
                    Manager = manager
                };
                report.ShowDialog(Application.Current.MainWindow);
            }
        }

        private void BtnExport_OnClick(object sender, RoutedEventArgs e)
        {
            var disks = IoUtility.GetDrivers();
            if (disks == null || !disks.Any())
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("InsertDisk"));
                return;
            }

            var index = GetSelectedItems();
            if (!index.Any()) return;
            if (IsGmp)
            {
                var login = new FrmAuth();
                var dr = login.ShowDialog(Application.Current.MainWindow);
                if (dr == null || !dr.Value) return;
            }

            TriggerButtonsStatus(false);
            Task.Run(() =>
            {
                //获取所选文件
                var files = GetFiles((from f in index select f.FilePath).ToList());

                if (files.Any())
                {
                    var disk = disks.First();
                    var tp = Path.Combine(disk.Name, ExportPath);
                    try
                    {
                        if (!Directory.Exists(tp)) Directory.CreateDirectory(tp);
                        var len = _getFilesSpace(files);
                        if (len > disk.Usable)
                        {
                            TriggerButtonsStatus(true);
                            _notify.ShowError(string.Format(LanguageManager.GetLanguageValue("InsertDiskLess"), disk.Name));
                            return;
                        }

                        foreach (var file in files)
                        {
                            // ReSharper disable once AssignNullToNotNullAttribute
                            var tf = Path.Combine(tp, Path.GetFileName(file));
                            if (IsGmp)
                            {
                                if (File.Exists(tf)) File.Delete(tf);
                                using (var zip = new ZipFile(tf))
                                {
                                    zip.Password = "labthink-staff";
                                    zip.AddFile(file);
                                    zip.Save();
                                }
                            }
                            else
                            {
                                File.Copy(file, tf, true);
                            }
                        }

                        var log = new OperateLog
                        {
                            Content = string.Format(LanguageManager.GetLanguageValue("ExportFiles"), ProcessFilesName(files)),
                            OpType = "Data",
                            LogTime = DateTime.Now
                        };

                        LogRepository.AddLog(log);
                        _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                        _logger.Error(exception);
                        _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                    }
                }
                else
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                }

                TriggerButtonsStatus(true);
            });
        }

        private long _getFilesSpace(IEnumerable<string> files)
        {
            long len = 0;
            foreach (var file in files)
            {
                var fi = new System.IO.FileInfo(file);
                len += fi.Length;
            }

            return len;
        }

        private void BtnExportRow_OnClick(object sender, RoutedEventArgs e)
        {
            var disks = IoUtility.GetDrivers();
            if (disks == null || !disks.Any())
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("InsertDisk"));
                return;
            }

            var btn = sender as Button;
            var sp = btn?.Parent as StackPanel;
            if (!(sp?.DataContext is TestIndex ti)) return;
            if (IsGmp)
            {
                var login = new FrmAuth();
                var dr = login.ShowDialog(Application.Current.MainWindow);
                if (dr == null || !dr.Value) return;
            }

            TriggerButtonsStatus(false);
            Task.Run(() =>
            {
                //获取所选文件
                var files = GetFiles(new List<string> { ti.FilePath });
                if (files.Any())
                {
                    var disk = disks.First();
                    var fi = new System.IO.FileInfo(files.First());
                    if (fi.Length > disk.Usable)
                    {
                        TriggerButtonsStatus(true);
                        _notify.ShowError(string.Format(LanguageManager.GetLanguageValue("InsertDiskLess"), disk.Name));
                        return;
                    }
                    var tp = Path.Combine(disk.Name, ExportPath);
                    try
                    {
                        if (!Directory.Exists(tp)) Directory.CreateDirectory(tp);
                        foreach (var file in files)
                        {
                            // ReSharper disable once AssignNullToNotNullAttribute
                            var tf = Path.Combine(tp, Path.GetFileName(file));
                            if (IsGmp)
                            {
                                if (File.Exists(tf)) File.Delete(tf);
                                using (var zip = new ZipFile(tf))
                                {
                                    zip.Password = "labthink-staff";
                                    zip.AddFile(file);
                                    zip.Save();
                                }
                            }
                            else
                            {
                                File.Copy(file, tf, true);
                            }
                        }

                        var log = LanguageManager.GetLanguageValue("ExportFiles", Path.GetFileName(files[0]));
                        LogRepository.AddLog(log, "Data");
                        _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                        _logger.Error(exception);
                        _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                    }
                }
                else
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                }

                TriggerButtonsStatus(true);
            });
        }

        private void BtnUpload_OnClick(object sender, RoutedEventArgs e)
        {
            var indexs = GetSelectedItems();
            if (!indexs.Any()) return;
            var files = (from f in indexs select f.FilePath).ToList();
            TriggerButtonsStatus(false);
            var r = DataShieldClient.AddFiles(files);
            if (r < 0)
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
            }
            else
            {
                _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                LogRepository.AddLog(
                    LanguageManager.GetLanguageValue("OP-AddFilesToSend", files.Count), "Data");
            }
            TriggerButtonsStatus(true);
        }

        private void BtnUploadRecord_OnClick(object sender, RoutedEventArgs e)
        {
            var frm = new FrmSendRecord();
            frm.ShowDialog(Application.Current.MainWindow);
        }

        private void BtnUploadRow_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var sp = btn?.Parent as StackPanel;
            if (!(sp?.DataContext is TestIndex ti)) return;
            TriggerButtonsStatus(false);
            var r = DataShieldClient.AddFiles(new List<string> { ti.FilePath });
            if (r < 0)
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
            }
            else
            {
                _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                LogRepository.AddLog(
                    LanguageManager.GetLanguageValue("OP-AddFileToSend", ti.FilePath), "Data");
            }

            TriggerButtonsStatus(true);
        }

        private void BtnSign_OnClick(object sender, RoutedEventArgs e)
        {
            var index = GetSelectedItems();
            if (index.Count == 0) return;
            var r = index.First().ESignal;
            foreach (var idn in index)
            {
                if (idn.ESignal != r)
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("NotBatchSignal"));
                    return;
                }
            }

            var login = new FrmAuth();
            var dr = login.ShowDialog(Application.Current.MainWindow);
            if (dr == null || !dr.Value) return;
            var qs = new List<QuerySign>();
            foreach (var idx in index)
            {
                qs.Add(new QuerySign { FilePath = idx.FilePath, TestId = idx.TestId });
            }

            var frm = new FrmSignal { Querys = qs };
            frm.ShowDialog(Application.Current.MainWindow);
            BtnQuery_OnClick(null, null);
        }

        private void BtnSignRow_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var sp = btn?.Parent as StackPanel;
            if (!(sp?.DataContext is TestIndex ti)) return;
            var login = new FrmAuth();
            var dr = login.ShowDialog(Application.Current.MainWindow);
            if (dr == null || !dr.Value) return;
            var frm = new FrmSignal { Querys = new List<QuerySign> { new QuerySign { FilePath = ti.FilePath, TestId = ti.TestId } } };
            frm.ShowDialog(Application.Current.MainWindow);
            //SignClickedHandler?.Invoke(this, ti);
            BtnQuery_OnClick(null, null);
        }

        private void BtnTagAndRemarkRow_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var sp = btn?.Parent as StackPanel;
            if (!(sp?.DataContext is TestIndex ti)) return;
            //TagAndRemarkClickedHandler?.Invoke(this, ti);
            var detail = new FrmTagAndRemarkDetail { Ti = ti };
            var r = detail.ShowDialog(Application.Current.MainWindow);
            if (r.HasValue && r.Value)
            {
                _initDatas();
            }
        }

        private void BtnDelete_OnClick(object sender, RoutedEventArgs e)
        {
            var index = GetSelectedItems();
            if (!index.Any()) return;
            //if (MessageBox.Show(Resources.GetLanguageValue("TestDataDeleteAlert"), "", MessageBoxButton.OKCancel) != MessageBoxResult.OK) return;
            if (MyMessageBox.Show(Application.Current.MainWindow, LanguageManager.GetLanguageValue("TestDataDeleteAlert"), MyMessageBoxButton.OkCancel,
                    MyMessageBoxImage.Warning, MyMessageBoxDefaultButton.Ok) != MyMessageBoxResult.Ok) return;
            TriggerButtonsStatus(false);
            var ids = (from i in index select i.TestId).ToList();
            var r = HistoryRepository.DeleteIndexs(ids);
            if (r < 0)
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
            }
            else
            {
                _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                //var str = "";
                //foreach (var id in ids)
                //{
                //    str += id;
                //    str += ",";
                //}
                LogRepository.AddLog(
                    LanguageManager.GetLanguageValue("OP-DeleteTests", ids.Count), "Data");
                BtnQuery_OnClick(null, null);
            }

            TriggerButtonsStatus(true);
        }

        private void BtnReset_OnClick(object sender, RoutedEventArgs e)
        {
            TestName.Value = string.Empty;
            SampleName.Value = string.Empty;
            SampleBatch.Value = string.Empty;
            SampleNo.Value = string.Empty;
            OpName.Value = string.Empty;
            Remark.Value = string.Empty;
            Tag1.Value = string.Empty;
            StartTime.DpPicker.SelectedDate = null;
            EndTime.DpPicker.SelectedDate = null;
            Sign.CbbChildBox.SelectedValue = null;
            TestType.CbbChildBox.SelectedValue = null;
            if (Common.SelfQuerys == null)
            {
                Common.SelfQuerys = BaseRepository.SelfQuery;
            }

            foreach (var sq in Common.SelfQuerys)
            {
                if (WpQuerys.FindName("Cbb" + sq.ColumnName) is UcComboBox cbb)
                    cbb.CbbChildBox.SelectedValue = null;
            }

            BtnQuery_OnClick(null, null);
            //_notify.ShowSuccess(Resources.GetLanguageValue("ActionSuccess"));
        }

        private void RbPro_Checked(object sender, RoutedEventArgs e)
        {
            if (_queryData == null) return;
            _queryData.PageCount = -1;
            _queryData.PageIndex = 1;
            _initDatas();
        }

        private void RbAuto_Checked(object sender, RoutedEventArgs e)
        {
            if (_queryData == null) return;
            _queryData.PageCount = 10;
            _queryData.PageIndex = 1;
            _initDatas();
        }

        private void _initDatas()
        {
            TriggerButtonsStatus(false);
            GridData.ItemsSource = null;
            BoxHeader.IsChecked = false;
            var data = HistoryRepository.GetIndex(_queryData);
            if (data.InnerList == null || !data.InnerList.Any())
            {
                pager.TotalItemCount = 0;
                pager.TotalPageCount = 0;
                pager.PageIndex = 0;
            }
            else
            {
                GridData.ItemsSource = data.InnerList;
                pager.TotalItemCount = data.TotalCount;
                pager.TotalPageCount = data.PageCount;
                pager.PageIndex = _queryData.PageIndex;
            }

            TriggerButtonsStatus(true);
        }

        private void InitFrame()
        {
            if (Common.SelfQuerys == null)
            {
                Common.SelfQuerys = BaseRepository.SelfQuery;
            }

            if (Common.SelfQuerys != null)
            {
                while (Common.LanguagesFromDb == null)
                {
                    Thread.Sleep(50);
                }

                //var bind = new Binding("ActualWidth") { ElementName = "TestName" };
                var fs = (double)Resources["SmallDisplayFont"];
                var fst = (double)Resources["SubDisplayFont"];

                foreach (var sq in Common.SelfQuerys)
                {
                    //查询条件
                    var cmb = new UcComboBox
                    {
                        Margin = new Thickness(10, 3, 10, 3),
                        //Width = TestName.ActualWidth,
                        Tag = Common.LanguagesFromDb.Single(l => l.LanguageId == sq.LanguageId).Text,
                        FontSize = fs
                    };

                    if (sq.DataNo == 190105)
                    {
                        var tvs = new List<TextAndValue>();
                        tvs.Add(new TextAndValue { Text = "--", Value = "-1" });
                        foreach (var d in Common.Pls)
                        {
                            tvs.Add(new TextAndValue { Text = d + "", Value = d + "" });
                        }
                        cmb.Init(tvs, "Text", "Value");
                    }
                    else
                    {
                        var slts = new List<RtdData> { new RtdData { No = -1, Data1 = "--" } };
                        var inx = 1;
                        var key = sq.LanguageId + inx;
                        var text = Common.LanguagesFromDb.Single(l => l.LanguageId == key).Text;
                        while (key != text)
                        {
                            slts.Add(new RtdData { No = inx, Data1 = text });
                            inx++;
                            key = sq.LanguageId + inx;
                            var lan = Common.LanguagesFromDb.SingleOrDefault(l => l.LanguageId == key);
                            if (lan == null) break;
                            text = lan.Text;
                            //slts.Add(new RtdData { No = inx, Data1 = text });
                        }

                        cmb.CbbChildBox.ItemsSource = slts;
                        cmb.CbbChildBox.DisplayMemberPath = "Data1";
                        cmb.CbbChildBox.SelectedValuePath = "No";
                    }

                    WpQuerys.RegisterName("Cbb" + sq.ColumnName, cmb);
                    WpQuerys.Children.Insert(0, cmb);

                    //显示列
                    var dtc = new DataGridTextColumn
                    {
                        ElementStyle = Resources["DataGridTextCenter"] as Style
                    };

                    var binding = new Binding("SelfQuery")
                    {
                        Converter = FindResource("SelfQueryConverter") as IValueConverter,
                        ConverterParameter = sq.DataNo + ""
                    };

                    dtc.Binding = binding;
                    dtc.Header = new TextBlock
                    {
                        HorizontalAlignment = HorizontalAlignment.Left,
                        FontSize = fst,
                        Text = cmb.Tag + ""
                    };

                    GridData.Columns.Insert(4, dtc);
                }
            }

            if (Common.Permissions.All(p => p.Code != "Per_HistoryDataExport".Clear()))
                BtnExport.Visibility = Visibility.Collapsed;

            if (Common.Permissions.All(p => p.Code != "Per_HistoryDataUpload".Clear()))
            {
                BtnUpload.IsEnabled = false;
                BtnUploadRecord.IsEnabled = false;
                BtnUpload.Tag = false;
                BtnUploadRecord.Tag = false;
            }
            else
            {
                BtnUpload.Tag = true;
                BtnUploadRecord.Tag = true;
            }

            if (Common.Permissions.All(p => p.Code != "Per_HistoryDataDelete".Clear()))
            {
                BtnDelete.Visibility = Visibility.Collapsed;
                BtnDelete.Tag = false;
            }
            else
            {
                BtnDelete.Tag = true;
            }

            if (Common.Permissions.All(p => p.Code != "Per_HistoryDataSign".Clear()))
            {
                BtnSign.IsEnabled = false;
                BtnSign.Tag = false;
            }
            else
            {
                BtnSign.Tag = true;
            }

            if (Common.Permissions.All(p => p.Code != "Report".Clear()))
            {
                BtnReport.Visibility = Visibility.Collapsed;
            }
        }

        private void TriggerButtonsStatus(bool status)
        {
            Dispatcher?.Invoke(() =>
            {
                Loading.Visibility = status ? Visibility.Collapsed : Visibility.Visible;

                BtnSign.IsEnabled = status & Convert.ToBoolean(BtnSign.Tag);
                BtnExport.IsEnabled = status;
                BtnQuery.IsEnabled = status;
                BtnReport.IsEnabled = status;
                BtnUpload.IsEnabled = status & Convert.ToBoolean(BtnUpload.Tag);
                if (BtnDelete.Visibility == Visibility.Visible)
                {
                    BtnDelete.IsEnabled = status & Convert.ToBoolean(BtnDelete.Tag);
                }

                if (BtnSign.Visibility == Visibility.Visible)
                {
                    BtnSign.IsEnabled = status & Convert.ToBoolean(BtnSign.Tag);
                }
            });
        }

        private List<TestIndex> GetSelectedItems()
        {
            var selected = new List<TestIndex>();
            Dispatcher?.Invoke(() =>
            {
                foreach (var item in GridData.Items)
                {
                    var i = GridData.Columns[0].GetCellContent(item);
                    DataGridTemplateColumn temp = (GridData.Columns[0] as DataGridTemplateColumn);
                    if (i != null)
                    {
                        var cb = temp?.CellTemplate.FindName("cbStatus", i) as CheckBox;
                        if (cb?.IsChecked != null && cb.IsChecked.Value)
                        {
                            selected.Add(item as TestIndex);
                        }
                    }
                }
            });

            return selected;
        }

        private List<string> GetFiles(List<string> files)
        {
            if (files == null || !files.Any())
            {
                var index = GetSelectedItems();
                if (!index.Any()) return null;
                files = (from f in index select f.FilePath).ToList();
            }

            for (int i = 0; i < files.Count; i++)
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                files[i] = Path.Combine(Common.DbPath, Path.GetFileName(files[i]));
            }
            return files;
        }

        private string ProcessFilesName(IEnumerable<string> files)
        {
            return string.Join(",", files.Select(Path.GetFileName));
        }
    }
}
